﻿using MediatR;
using WMS.API.Application.Command.SystemUser;
using WMS.Domain.Entities.SystemUser;
using WMS.ErrorCode;
using WMS.Interfactructure.Interfaces;
using System.Linq;

namespace WMS.API.Application.CommandHandlers.SystemUser
{
    /// <summary>
    /// 财务明细命令处理器
    /// </summary>
    public class FinancialdetailsHandler : IRequestHandler<GetFinancialdetailsQuery, APIResult<APIPaging<Financialdetails>>>
    {
        /// <summary>
        /// 财务明细仓储（操作数据库）
        /// </summary>
        private readonly IBaseRepository<Financialdetails> baseRepository;
        /// <summary>
        /// 构造函数，注入财务明细仓储
        /// </summary>
        /// <param name="baseRepository">财务明细仓储（操作数据库）</param>
        public FinancialdetailsHandler(IBaseRepository<Financialdetails> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 查询财务明细
        /// </summary>
        /// <param name="request">查询财务明细请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>API响应结果</returns>
        public Task<APIResult<APIPaging<Financialdetails>>> Handle(GetFinancialdetailsQuery request, CancellationToken cancellationToken)
        {
            // 1. 初始化API响应
            APIResult<APIPaging<Financialdetails>> res = new APIResult<APIPaging<Financialdetails>>("查询财务明细成功")
            {
                Data = new APIPaging<Financialdetails>()
            };
            try
            {
                IQueryable<Financialdetails> query = baseRepository.GetAll();

                // 2. 根据搜索字段和搜索值进行过滤
                if (!string.IsNullOrEmpty(request.SearchField) && !string.IsNullOrEmpty(request.SearchValue))
                {
                    switch (request.SearchField.ToLower())
                    {
                        case "usercode":
                            query = query.Where(f => f.UserCode.Contains(request.SearchValue));
                            break;
                        case "typeof":
                            query = query.Where(f => f.Typeof.Contains(request.SearchValue));
                            break;
                        case "depositmethod":
                            query = query.Where(f => f.DepositMethod.Contains(request.SearchValue));
                            break;
                        case "trackingnumber":
                            query = query.Where(f => f.TrackingNumber.Contains(request.SearchValue));
                            break;
                        case "warehousename":
                            query = query.Where(f => f.WarehouseName.Contains(request.SearchValue));
                            break;
                        case "tariffstandard":
                            query = query.Where(f => f.TariffStandard.Contains(request.SearchValue));
                            break;
                        case "feedetailed":
                            query = query.Where(f => f.FeeDetailed.Contains(request.SearchValue));
                            break;
                        case "itemdetails":
                            query = query.Where(f => f.ItemDetails.Contains(request.SearchValue));
                            break;
                        default:
                            break;
                    }
                }

                // 3. 根据时间范围进行过滤
                if (request.StartTime.HasValue)
                {
                    query = query.Where(f => f.StartTime >= request.StartTime.Value);
                }
                if (request.EndTime.HasValue)
                {
                    query = query.Where(f => f.StartTime <= request.EndTime.Value);
                }

                // 4. 计算总记录数和总页数
                int totalRecords = query.Count();
                int totalPages = (int)Math.Ceiling(totalRecords / (double)request.PageSize);

                // 5. 应用分页
                List<Financialdetails> pagedData = query
                    .Skip((request.CurrentPage - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                res.Data.TotalCount = totalRecords;
                res.Data.TotalPage = totalPages;
                res.Data.PageData = pagedData;

                // 6. 如果没有数据，更新响应信息
                if (!res.Data.PageData.Any())
                {
                    res.Message = "没有找到任何财务明细";
                    res.Code = ResultCode.Failed;
                }
            }
            catch (Exception ex)
            {
                // 7. 异常处理，更新响应信息
                res.Message = $"查询财务明细失败: {ex.Message}";
                res.Code = ResultCode.Failed;
            }
            // 8. 返回API响应结果
            return Task.FromResult(res);
        }
    }
}

